package com.ruike.alisurface.ui.payPage;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.coll.CollectionAPI;
import com.alipay.iot.sdk.coll.TradeDataConstants;
import com.alipay.iot.sdk.payment.PaymentAPI;
import com.alipay.zoloz.smile2pay.service.Zoloz;
import com.alipay.zoloz.smile2pay.service.ZolozCallback;
import com.cunoraz.gifview.library.GifView;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.AlipayBean;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.utils.MYUtiles;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static com.alipay.iot.sdk.coll.TradeDataConstants.TradeFailType.NETWORK_EXCEPTION;
import static com.alipay.iot.sdk.coll.TradeDataConstants.TradeFailType.NONE;

/**
 * Author: voodoo
 * CreateDate: 2020-04-08
 * Description: 刷脸页
 */
public class PayAlFaceActivity extends BaseAty {
    @BindView(R.id.payFace_startCamera_gifv)
    GifView startCameraGifv;

    public static final String KEY_INIT_RESP_NAME = "zim.init.resp";
    public static final String CAPTURE_UI_MODE = "captureUIMode";
    static final String CODE_SUCCESS = "1000";
    static final String CODE_TIMEOUT = "1004";

    static final String TXT_OTHER = "抱歉未支付成功，请重新支付";
    Zoloz zoloz;//刷脸对象
    private MyCountDownTimer countDownTimer;//倒计时
    List<CarGoodsBeans> paycarlist;//商品信息
    String mchid;// mchid 机器账号id
    Handler messageHandler;//消息处理handler

    Double pay_fee;//支付金额
    String orderId;//订单号
    ShopDetailBean shopDetailBean;//出货信息类
    String fToken;//刷脸的ftoken
    private long startTime, lastTime, actTime;//刷脸的开始  结束 用时 时间

    AlertDialog alertDialog;//提示弹框
    private Double order_money;//订单金额
    private Double actual_money;//实付金额
    private Double discount;//优惠金额

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_face;
    }


    @Override
    protected void initViews() {
        L.i("刷脸支付页==" + this.getClass().getName());
        startCameraGifv.setVisibility(View.VISIBLE);
        startCameraGifv.play();
        mchid = ShareUtils.getInstance().getString(ShareKey.MCH_ID, "");
        HandlerShow();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(35, null, isFace ? null : SelectPayTypeActivity.class);

    }

    @Override
    protected void initData() {
        paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        SystemClock.sleep(200);
        if (paycarlist == null) {
            L.i("查询商品数据异常");
            startCountdownTimer(0, null,  isFace ? null : SelectPayTypeActivity.class);
            return;
        }

        if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
            L.i("按货道展示上传信息");
            getPayinfoCode();
        } else {

            L.i("按商品类型展示上传信息");
            getPayTypeinfoCode();
        }
        countDownTimer = new MyCountDownTimer(10_000, 10_000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (!PayAlFaceActivity.this.isFinishing()) {
                    startCameraGifv.pause();
                    new CustomDialog.Builder(PayAlFaceActivity.this)
                            .setTitle("错误提示")
                            .setMessage("很抱歉，启动摄像头异常，请重试或联系管理员！")
                            .create().show();
                }
            }
        };
        countDownTimer.start();
    }


    @Override
    public void doEventBusResult(MsgEventBus event) {

    }


    private void HandlerShow() {
        messageHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case 1:
                        startCameraGifv.pause();
                        startCameraGifv.setVisibility(View.GONE);
                        break;
                    case 2:
//                        ToastUtils.ToastCostom(PayAlFaceActivity.this, "网络不佳，请使用微信支付宝扫码支付！！", "1", 3000);
                        showErrorTip("网络不佳，请使用微信支付宝扫码支付！！");
                        startAty();
                        break;
                    case 3:
                        if (alertDialog != null) {
                            alertDialog.dismiss();
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString("pay_type", "alface");
                        bundle.putSerializable("orderBeanData", shopDetailBean);
                        startActivity(PayShowShopActivity.class, bundle);
                        finish();
                        break;
                    case 4:
                        showErrorTip("网络不佳，请稍后重试！！");
                        startAty();
                        break;
                    case 5:
                        alt();
                        break;
                    case 6:
                        startAty();
                        break;
                    case 7:
                        showErrorTip("支付失败");
                        startAty();
                        break;

                    case 10:
                        MchApiHttp.getPayResult(PayAlFaceActivity.this, orderId);
                        messageHandler.sendEmptyMessageDelayed(10, 3000);
                        break;
                }

                return false;
            }
        });
    }

    /**
     * 区分跳转页面
     */
    public void startAty() {
        startActivity(isFace ? PayForQRCodeActivity.class : SelectPayTypeActivity.class, null);
        finish();
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        JSONObject object = null;
        try {
            object = new JSONObject(requestJsonStr);
            String code = object.getString("code");
            String data = object.optString("data");
            if (requestUrl.endsWith("CreareSmilePayOrder") || requestUrl.endsWith("CreateForProduct")) {
                JSONObject datas = new JSONObject(data);
                pay_fee = datas.optDouble("Pay_fee");
                orderId = datas.optString("orderId");
                startAlFace();
            } else if (requestUrl.endsWith("Initialize")) {
                JSONObject datas = new JSONObject(data);
                String SzimId = datas.getString("zimId");
                String SzimInitClientData = datas.getString("zimInitClientData");

                //如果返回code为0 就唤醒人脸识别s
                if (code.equals("0")) {
                    L.i("=====tjf====发送成功 返回结果");
//                        alertDialog.dismiss();
//                    messageHandler.sendEmptyMessage(1);
                    Smile(SzimId, SzimInitClientData);
                }
            } else if (requestUrl.endsWith("StartSmilePay")) {
                /*
                 * 如果支付成功之后返回我正确的信号，进行出货跳转界面的操作，出货之后跳，更新库存，上传订单信息，出货的方法
                 */
                lastTime = System.currentTimeMillis();
                actTime = lastTime - startTime;
                L.i("tjf====sendPayOrder: 交易时间：" + (int) actTime);
                //进行埋点上报的工作
                CollectionAPI collectionAPI = APIManager.getInstance().getCollectionAPI();
                collectionAPI.reportTradeData(true, NONE, null, TradeDataConstants.NetworkType._4G, (int) actTime);
                AlipayBean.DataBean.OrderBean orderBean = JsonPro_News_Entity(requestJsonStr).getData().getOrder();
                setShopData(orderBean);
                String acty_config = orderBean.getActivity_config();
                String acty_id = orderBean.getActivity_id();
                setHuoDongoing(acty_config, acty_id);
                try {
                    L.i("tjf===SlotNote-----------:" + "order_money--"
                                    + order_money + "---actual_money---" + actual_money + "--discount---" + discount,
                            "acty_config", acty_config, "acty_id", acty_id);
                } catch (Exception e) {
                    L.i("tjf===SlotNote-----------:" + "order_money--"
                            + order_money + "---actual_money---" + actual_money + "--discount---" + discount);
                }
                messageHandler.sendEmptyMessage(3);
            } else if (requestUrl.endsWith("getPayResult")) {
                messageHandler.removeCallbacksAndMessages(null);
                CollectionAPI collectionAPI = APIManager.getInstance().getCollectionAPI();
                collectionAPI.reportTradeData(true, NONE, null, TradeDataConstants.NetworkType._4G, (int) actTime);
                messageHandler.sendEmptyMessage(3);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    int codecount = 0;//第一次进入code==2 的时候的判断

    @Override
    public void onError(String requestUrl, String errorMsg, String data) {
        super.onError(requestUrl, errorMsg, data);
        L.i("Error====" + requestUrl);
        if (requestUrl.endsWith("StartSmilePay")) {
            try {
                if (data != null) {
                    JSONObject json = new JSONObject(data);
                    String code = json.optString("code");
                    L.i("==返回码==" + code);
                    if (code.equals("2")) {
                        ++codecount;
                        if (codecount == 1) {
                            startCountdownTimer(30, null, isFace ? null : SelectPayTypeActivity.class);
                        }
                        showProgressDialog(getString(R.string.deductMoneyStr), false);
                        AlipayBean.DataBean.OrderBean orderBean = JsonPro_News_Entity(data).getData().getOrder();
                        setShopData(orderBean);
                        messageHandler.removeCallbacksAndMessages(null);
                        messageHandler.sendEmptyMessageDelayed(10, 3000);
                    } else {
                        lastTime = System.currentTimeMillis();
                        actTime = lastTime - startTime;
                        L.i("tjf===sendPayOrder: 交易超时的操作 ：" + (int) actTime);
                        //进行埋点上报的工作
                        CollectionAPI collectionAPI = APIManager.getInstance().getCollectionAPI();
                        collectionAPI.reportTradeData(false, NETWORK_EXCEPTION, null, TradeDataConstants.NetworkType._4G, (int) actTime);
                        messageHandler.sendEmptyMessage(2);
                    }
                } else {
                    L.i("Error====" + requestUrl + "   data 数据为空");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 出货信息的解析及保存
     *
     * @param orderBean
     */
    void setShopData(AlipayBean.DataBean.OrderBean orderBean) {
        orderId = orderBean.getOrderNo();
        L.i("   orderid---------" + orderId);
        order_money = orderBean.getTotal_fee();      //订单金额
        actual_money = orderBean.getPay_fee();         //实付金额
        discount = orderBean.getDiscount_fee();         //优惠金额
        shopDetailBean = new ShopDetailBean(orderId);
        shopDetailBean.setTotal_fee(order_money);
        shopDetailBean.setPay_fee(actual_money);
        shopDetailBean.setDiscount_fee(discount);
        shopDetailBean.setDetailOrderList(orderBean.getOrderDetails());
    }

    /**
     * 活动显示数据判断
     */
    public void setHuoDongoing(String acty_config, String acty_id) throws JSONException {
        if (TextUtils.isEmpty(acty_id)) {
            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "0");
            return;
        }

        if (acty_id.equals("1")) { // 转盘

            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "1");
            return;
        }

        if (TextUtils.isEmpty(acty_config)) {
            return;
        }
        if (acty_id.equals("2")) { //满减
            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "2");
            return;
        }
        if (acty_id.equals("3")) { //折扣
            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "3");
            return;
        }
    }

    //填写商户信息
    private HashMap<String, Object> mockInfo() {
        HashMap<String, Object> merchantInfo = new HashMap<>();
        merchantInfo.put("merchantId", "2088821660782062");//必填项，签约商户的pid。来自蚂蚁开放平台，示例："2088011211821038"
        merchantInfo.put("partnerId", "2088821660782062");//必填项，ISV的pid。对于自用型商户，填写签约商户的pid，和merchantId保持一致
        merchantInfo.put("appId", "2018110962091551");//必填项，支付宝分配给开发者的应用ID，和当面付请求的appid保持一致。
        merchantInfo.put("deviceNum", mchid);//必填项，商户机具终端编号，和当面付请求的terminal_id 保持一致
        merchantInfo.put("terminal_id", mchid);
        merchantInfo.put("brandCode", "rk");
        merchantInfo.put("storeCode", mchid);//可选，商户门店编号，和当面付请求的store_id保持一致。
        return merchantInfo;
//        merchantInfo.put("alipayStoreCode","XXX");//可选，支付宝内部门店编号，如2017100900077000000045877777，和当面付请求中的alipay_store_id保持一致。
    }

    /**
     * 解析数据。生成订单号
     */
    public void getPayinfoCode() {
        try {
            //判断数据是否已经存在
            String result = "";
            for (int i = 0; i < paycarlist.size(); i++) {
                result += paycarlist.get(i).getSlotIndexs() + ",";
            }
            Map<String, Integer> map;
            List list1 = new ArrayList();
            //将字符串转化为字符数组
            String[] chars = result.split(",");
            //创建一个HashMap名为hm
            HashMap<String, Integer> hm = new HashMap();
            //定义一个字符串c，循环遍历遍历chars数组
            for (String c : chars) {
                if (!hm.containsKey(c)) {
                    hm.put(c, 1);
                } else {
                    //否则获得c的值并且加1
                    hm.put(c, hm.get(c) + 1);
                }
                //或者上面的if和else替换成下面这一行
                /*  hm.put(c,hm.containsKey(c) ? hm.get(c)+1:1);*/
            }
            //上传商品详情 去的订单号 显示成二维码
            for (String key : hm.keySet()) {
                map = new HashMap<>();
                //hm.keySet()代表所有键的集合,进行格式化输出
                map.put("Quantity", hm.get(key));
                map.put("SlotIndex", Integer.parseInt(String.valueOf(key)));
                list1.add(map);
            }
            HashMap<String, Object> maps = new HashMap<>();
            maps.put("MchId", mchid);
            maps.put("OrderDetails", GsonUtils.list2JsonArrayNotNulls(list1));
            MchApiHttp.postCreareSmilePayOrder(this, maps);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    /**
     * 按类型下单
     */
    public void getPayTypeinfoCode() {
        try {
            //判断数据是否已经存在

            Map<String, Object> map;
            List list1 = new ArrayList();
            //上传商品详情 去的订单号 显示成二维码
            for (int i = 0; i < paycarlist.size(); i++) {
                map = new HashMap<>();
                map.put("Quantity", 1);
                map.put("productid", paycarlist.get(i).getProductid());
                List<Integer> slotIndexs = new ArrayList<>();
                L.i("slotIndexs====", paycarlist.get(i).getSlotIndexs());
                JSONArray jsonArray = new JSONArray(paycarlist.get(i).getSlotIndexs());
                for (int c = 0; c < jsonArray.length(); c++) {
                    slotIndexs.add(Integer.parseInt(jsonArray.opt(c) + ""));
                }
                map.put("slotIndexs", slotIndexs);
                list1.add(map);
            }
            HashMap<String, Object> maps = new HashMap<>();
            maps.put("mchid", ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
            maps.put("OrderDetails", GsonUtils.list2JsonArrayNotNulls(list1));
            maps.put("IsFace", true);
            MchApiHttp.postGoodsTypeQRCode(this, maps);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    /**
     * 启动刷脸
     */
    public void startAlFace() {
        /*
         * 1. 在商户APP启动时调用刷脸应用预热
         */
        zoloz = Zoloz.getInstance(getApplicationContext());
        zoloz.zolozInstall(mockInfo());

//        Toast.makeText(this, "刷脸预热完成", Toast.LENGTH_SHORT).show();

        /*
         * 2.获取设备信息
         */
        zoloz.zolozGetMetaInfo(mockInfo(), new ZolozCallback() {
            @Override
            public void response(Map map) {
                String code = (String) map.get("code");
                String metaInfo = (String) map.get("metainfo");
                L.i(" 刷脸设备  response: 获取设备信息===" + code + "=====" + metaInfo);
//                Toast.makeText(MedicalImgShowActivity.this, "response: 获取设备信息==="+ code + "=====" + metaInfo, Toast.LENGTH_SHORT).show();
                if (CODE_SUCCESS.equalsIgnoreCase(code) && metaInfo != null) {
                    /*
                     * 3.将metaInfo发送给商户服务端，由商户服务端发起刷脸初始化OpenAPI的调用
                     */

                    MchApiHttp.getInitialize(PayAlFaceActivity.this, metaInfo);

                }
            }
        });

    }

    /**
     * 发起刷脸支付请求.
     *
     * @param txt toast文案
     */
    void promptText(final String txt) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_LONG).show();
            }
        });
    }


    /**
     * 唤起人脸识别
     */
    private void Smile(String zimId, String protocal) {
//        promptText("唤起人脸识别方法执行");
        Map<String, String> params = new HashMap<>();
        params.put(KEY_INIT_RESP_NAME, protocal);
        params.put(CAPTURE_UI_MODE, "0"); // 刷脸UI模式：0-最早版本，自动开始刷脸
        zoloz.zolozVerify(zimId, params, new ZolozCallback() {
            @Override
            public void response(Map map) {
                if (map == null) {
                    promptText(TXT_OTHER);
                    messageHandler.sendEmptyMessage(6);
                    return;
                }
                L.i("===tjf===Smile: 方法执行=map==" + map.toString());
                String code = (String) map.get("code");
                fToken = (String) map.get("ftoken");
                L.i("===tjf===Smile: 方法执行===" + fToken + "===" + "===code===" + code);
                //刷脸成功
                if (CODE_SUCCESS.equalsIgnoreCase(code) && fToken != null) {
                    L.i("===tjf===Smile:唤起人脸识别: ===fToken===" + fToken + "===code===" + code);
                    /*
                     * 发送订单信息 并完成支付
                     */
                    startTime = System.currentTimeMillis();

                    messageHandler.sendEmptyMessage(5);

                } else if (CODE_TIMEOUT.equalsIgnoreCase(code)) {


                    messageHandler.sendEmptyMessage(2);
                } else {

                    messageHandler.sendEmptyMessage(6);
                }
            }
        });
    }


    /**
     * 加载数据是提示
     */
    private void alt() {
        showProgressDialog(getString(R.string.deductMoneyStr), false);
        sendPayOrder();
    }


    /**
     * 识别后的订单信息上传
     */
    public void sendPayOrder() {
        try {
            /*
             * 加签的工作
             */
            PaymentAPI api = APIManager.getInstance().getPaymentAPI();

            int monry = Integer.parseInt(MYUtiles.yuanToFen(pay_fee));
            L.i("tjf====sendPayOrder: 总金额：" + pay_fee);
            String priceyuan = MYUtiles.fenToYuan(monry);
            L.i("tjf==fToken=" + api.signWithDelegated(fToken, priceyuan) + "=====" + priceyuan);
            String data = api.signWithDelegated(fToken, priceyuan);
            JSONObject jsonObject = new JSONObject(data);
            String errcode = jsonObject.optString("errcode");
            if (errcode != null) {
            }
            //2上传订单信息
            HashMap<String, Object> mas = new HashMap<>();
            mas.put("OrderNo", orderId);
            mas.put("ftoken", fToken);
            mas.put("terminal_id", mchid);
            mas.put("store_id", mchid);
            mas.put("terminal_params", api.signWithDelegated(fToken, priceyuan));


            MchApiHttp.postStartSmilePay(this, mas);


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //实体类的转换
    public AlipayBean JsonPro_News_Entity(String str) {
        return GsonUtils.json2Model(str, AlipayBean.class);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (startCameraGifv!=null){
            startCameraGifv.pause();
        }
        if (countDownTimer != null) {
            L.i("tjf====countDownTimer  换起摄像头 关闭弹框提示倒计时");
            countDownTimer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        L.i("tjf====messageHandler  销毁页面");
        if (messageHandler != null) {
            messageHandler.removeCallbacksAndMessages(null);
        }
    }
}
